package com.ncut.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.ncut.constant.MessageConstant;
import com.ncut.dto.UserLoginDTO;
import com.ncut.entity.User;
import com.ncut.exception.LoginFailedException;
import com.ncut.properties.WeChatProperties;
import com.ncut.utils.HttpClientUtil;
import com.ncut.user.mapper.UserMapper;
import com.ncut.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @FileName UserServiceIMpl
 * @Description
 * @Author Sword
 * @date 2025-07-14
 **/

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获取当前微信用户openid
        String openid = getOpenid(userLoginDTO);

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断是否为新用户
        User user = userMapper.getByOpenid(openid);

        //如果为新用户，自动完成注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User getById(Long id) {
        return userMapper.getById(id);
    }

    /**
     * 统计用户数量
     *
     * @param map
     * @return
     */
    @Override
    public Integer countByMap(Map<String, Object> map) {
        return userMapper.countByMap(map);
    }

    /**
     * 获取微信用户openid
     *
     * @param userLoginDTO
     * @return
     */
    private String getOpenid(UserLoginDTO userLoginDTO) {
        Map<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret", weChatProperties.getSecret());
        param.put("js_code", userLoginDTO.getCode());
        param.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, param);

        String openid = JSON.parseObject(json).getString("openid");
        return openid;
    }
}
